package com.gome.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gome.entitiy.BMRecord;
import com.gome.exception.GlobalException;
import com.gome.exception.GlobalExceptionDatas;
import com.gome.mapper.BMMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BMService extends ServiceImpl<BMMapper,BMRecord> {
    private  final Logger logger=Logger.getLogger(this.getClass());

    public synchronized  String  createBM(String vcName, String wcym, String tableName, String ocCzy) {


        vcName = StringUtils.trimToEmpty(vcName);
        wcym = StringUtils.trimToEmpty(wcym);
        tableName = StringUtils.trimToEmpty(tableName);
        ocCzy = StringUtils.trimToEmpty(ocCzy);
        if("".equals(vcName)||"".equals(tableName)||"".equals(ocCzy)){

            logger.error( GlobalExceptionDatas.COMM_ERR_CODE_FAILD_CODE_BM_PARAM + "： " + " bmName: " + vcName + ", wcym: " + wcym + ", tableName: "
                    + tableName + ", userName: " + ocCzy);
           // throw new GlobalException(GlobalExceptionDatas.COMM_ERR_CODE_FAILD_CODE_BM_PARAM);
            throw new GlobalException("bmName or wcym or tableName or userName is null");
        }


        EntityWrapper<BMRecord>  wrapper= new EntityWrapper<BMRecord>();
        BMRecord record= new BMRecord();
        record.setDtCzrq(new Date());
        record.setOcCzy(ocCzy);
        record.setVcName(vcName);
        record.setOcYxbz("1");
        record.setVcTableName(tableName);

        wrapper.where("vc_name={0}",vcName).and("vc_tablename={0}",tableName).and("oc_yxbz={0}","1");

        BMRecord r= super.selectOne(wrapper);
        if(null==r){
            record.setOcSerial(1);
            super.insert(record);
        }else{
            r.setOcSerial(r.getOcSerial()+1);
            record=r;
            super.update(record,wrapper);
        }
        java.text.DecimalFormat yf = new java.text.DecimalFormat(wcym);
            return vcName +yf.format(record.getOcSerial());
        }


}
